package com.zmj.dubboannotation.productservice.productservice.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zmj.commoncore.dto.ProductCommentDTO;
import com.zmj.commoncore.utils.AttrValueUtil;
import com.zmj.dubboannotation.productservice.mapper.ProductCommentMapper;
import com.zmj.dubboannotation.productservice.mapper.SkuProductMapper;
import com.zmj.dubboannotation.serviceapi.api.ProductCommentService;
import com.zmj.dubboannotation.serviceapi.enums.ResultEnum;
import com.zmj.dubboannotation.serviceapi.exception.ProductException;
import com.zmj.dubboannotation.serviceapi.model.ProductComment;
import com.zmj.dubboannotation.serviceapi.model.SkuProduct;
import com.zmj.dubboannotation.serviceapi.vo.ProductVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by: meijun
 * Date: 2018/10/28 13:38
 */
@Service(interfaceClass = ProductCommentService.class)
@Component
@Slf4j
public class ProductCommentServiceImpl implements ProductCommentService {

    @Autowired
    private ProductCommentMapper productCommentMapper;

    @Autowired
    private SkuProductMapper skuProductMapper;

    @Override
    public PageInfo<ProductComment> findAllByProductId(String productId,Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<ProductComment> list = productCommentMapper.findAllByProductId(productId);
        PageInfo<ProductComment> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public List<ProductComment> findByQuery(ProductCommentDTO productCommentDTO) {
        return productCommentMapper.findByQuery(productCommentDTO);
    }

    @Override
    @Transactional
    public int save(ProductCommentDTO productCommentDTO) {
        SkuProduct skuProduct = skuProductMapper.selectByPrimaryKey(productCommentDTO.getSkuProductId());
        String attrValue = skuProduct.getAttrValue();

        ProductComment productComment = new ProductComment();
        BeanUtils.copyProperties(productCommentDTO,productComment);
        productComment.setBuyNurms(AttrValueUtil.getAttr(attrValue));
        int insert = productCommentMapper.insert(productComment);
        if(insert == 0) {
            throw  new ProductException(ResultEnum.PRPDUCT_COMMENT_CREATE_ERROR);
        }
        return insert;
    }

}
